<?php
namespace app\business\controller;
use app\business\model\BusinessLogin;
use think\Controller;
use think\Session;

class Login extends Controller
{
    //登录界面
    public function index()
    {
        if(request()->isPost()){
            $admin=new BusinessLogin();
            $data=input('post.');
//            验证功能
            $num=$admin->login($data);
            if($num==4){
               $this->error('该店铺目前尚未通过审核！');
            }elseif($num==2){
                $this->error('密码输入不正确');
            }elseif ($num==3) {

                $this->success('信息正确，正在为您跳转...','login/action');
            }
            else{
                $this->error('该用户不存在');
            }
        }
        return $this->fetch();
    }

    public function action()
    {
        if(!session('username')){
            $this->error('请先登录系统！','login/index');
        }

        //var_dump($_SESSION);die;
        $info = db('info')->find($_SESSION['think']['business_id']);

        if ($info['xcximg'] == '') {
          $this->test($_SESSION['think']['agent_id'],$_SESSION['think']['business_id']);
        }

        $username=Session::get('username');
        $this->assign('username',$username);
        return $this->fetch();
    }

//生成小程序二维码
       public function test($agent_id,$shop_id)
    {

            //图片名称
           $param = 32;
            $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            $imgname = "";
            for($i=0;$i<$param;$i++)
             {
                 $imgname .= $str{mt_rand(0,32)};    //生成php随机数
             }


        //判断文件夹是否存在
        $dir = 'public/uploads/shop/'.date('Ymd');
        if(!is_dir($dir))
        {
        $dir = iconv("UTF-8", "GBK", 'public/uploads/shop/'.date('Ymd'));
        mkdir ($dir,0777,true);
        }

        header("Content-type: image/jpeg");
        $setting = db('setting')->find($agent_id);
        $tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$setting['appid'].'&secret='.$setting['appsecret'];
        $Token = json_decode(httpGet($tokenUrl),true);
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$Token['access_token'];

        $data['path'] = 'pages/detail/detail?kind=0&id='.$shop_id.'&lng=&lat=';
        //$data['path'] = 'pages/index/index';
        $res = https_post($url,json_encode($data));
        //生成图片
        //echo $res;
        $imgDir = 'public/uploads/shop/';
        $filename = $imgDir.date('Ymd').'/'.$imgname.'.jpg';///要生成的图片名字
        $jpg = $res;//得到post过来的二进制原始数据

        $file = fopen($filename,"w");//打开文件准备写入
        $a = fwrite($file,$jpg);//写入
        $where['xcximg'] = date('Ymd').'/'.$imgname.'.jpg';
        $where['id'] = $shop_id;
        db('info')->update($where);

    }

    public function logout()
    {
        session(null);
        $this->success('退出成功！','index');
    }

}